import {
	type IAuthForm,
	type IAuthResponse,
	type IAuthWhoAmI,
	authResponseScheme
} from '@/types/auth.types'

import { axiosDefaults, axiosWithAuth } from '@/api/interceptors'

import {
	removeTokenStorage,
	saveTokenStorage
} from '@/services/auth-storage.service'

export const authService = {
	async main(req_data: IAuthForm) {
		const response = await axiosDefaults.post<IAuthResponse>(
			'/auth/login/',
			req_data
		)

		const data = authResponseScheme.parse(response.data)

		if (data.token) saveTokenStorage(data.token)

		return response
	},

	async logout() {
		const response = await axiosWithAuth.post('/auth/logout/')

		if (
			response.status === 204 ||
			response.status === 200 ||
			response.status === 401
		)
			removeTokenStorage()

		return response
	},

	async whoAmI() {
		return await axiosWithAuth.get<IAuthWhoAmI>('/auth/whoami/')
	}
}
